package ginsess

import (
	"github.com/gin-gonic/gin"
	ginsession "github.com/go-session/gin-session"
	"github.com/go-session/mongo"
	"github.com/go-session/session"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/log"
)

// Option session参数
type Option struct {
	Sign           string               `json:"sign,omitempty" yaml:"sign,omitempty"`                         // 签名
	CookieName     string               `json:"cookie_name,omitempty" yaml:"cookie_name,omitempty"`           // cookie 名字
	CookieLifeTime int                  `json:"cookie_life_time,omitempty" yaml:"cookie_life_time,omitempty"` // cookie 有效期单位秒
	Secure         bool                 `json:"secure,omitempty" yaml:"secure,omitempty"`                     // https 服务必须设置为true
	Domain         string               `json:"domain,omitempty" yaml:"domain,omitempty"`                     // Cookie域
	Expired        int64                `json:"expired,omitempty" yaml:"expired,omitempty"`                   // session过期时间
	Store          session.ManagerStore `json:"-,omitempty" yaml:"-,omitempty"`
	MgoStore       *MgoStore            `json:"mgo_store,omitempty" yaml:"mgo_store,omitempty"`
}

// MgoStore mongo存储
type MgoStore struct {
	URL      string `json:"url,omitempty" yaml:"url,omitempty"`
	DbName   string `json:"db_name,omitempty" yaml:"db_name,omitempty"`
	CollName string `json:"coll_name,omitempty" yaml:"coll_name,omitempty"`
}

// Sessions 注入session插件
func Sessions(so Option) gin.HandlerFunc {

	opt := make([]session.Option, 0)
	if so.Sign != "" {
		opt = append(opt, session.SetSign([]byte(so.Sign)))
	}
	if so.CookieName != "" {
		opt = append(opt, session.SetCookieName(so.CookieName))
	}
	if so.CookieLifeTime > 0 {
		opt = append(opt, session.SetCookieLifeTime(so.CookieLifeTime))
	}
	if so.Secure {
		opt = append(opt, session.SetSecure(so.Secure))
	}
	if so.Expired > 0 {
		opt = append(opt, session.SetExpired(so.Expired))
	}
	if so.MgoStore != nil {
		log.Debugf("++++++ %v", so.MgoStore)
		opt = append(opt, session.SetStore(mongo.NewStore(so.MgoStore.URL, so.MgoStore.DbName, so.MgoStore.CollName)))
	}

	return ginsession.New(opt...)
}

// FromContext 获取session
func FromContext(ctx *gin.Context) session.Store {
	return ginsession.FromContext(ctx)
}
